/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.raspberrypi.gpio.io;

import cn.hutool.core.util.ObjUtil;
import com.pi4j.context.Context;
import com.pi4j.io.gpio.digital.DigitalInput;
import com.pi4j.io.gpio.digital.DigitalOutput;
import com.pi4j.io.gpio.digital.DigitalState;
import com.pi4j.io.gpio.digital.PullResistance;
import lombok.AccessLevel;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;

/**
 * <b>(RaspberryPiDiodeLed)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023/2/13
 */
@SuppressWarnings("unused")
@FieldDefaults(level = AccessLevel.PRIVATE)
@Accessors(chain = true)
@Controller
@Mapping("/diode/")
public class RaspberryPiDiodeLed {
    @Inject
    Context pi4j;
    DigitalOutput led;
    /** PIN 18 = BCM 24 */
    static final int PIN_BUTTON = 24;
    /** PIN 15 = BCM 22 */
    static final int PIN_LED    = 26;

    @Mapping("/")
    public String led(boolean ledStatus) {
        init();

        if (ledStatus) {
            System.out.println("Led turn On");
            led.on();
        } else {
            led.off();
            System.out.println("Led turn Off");
        }
        return "Led On";
    }

    private void init() {
        if (ObjUtil.isNull(led)) {
            initLed();
            initButton();
        }
    }

    private void initLed() {
        var ledConfig = DigitalOutput.newConfigBuilder(pi4j)
                .id("led")
                .name("LED Flasher")
                .address(PIN_LED)
                .shutdown(DigitalState.LOW)
                .initial(DigitalState.LOW)
                .provider("pigpio-digital-output");

        led = pi4j.create(ledConfig);
    }

    private void initButton() {
        var buttonConfig = DigitalInput.newConfigBuilder(pi4j)
                .id("button")
                .name("Press button")
                .address(PIN_BUTTON)
                .pull(PullResistance.PULL_DOWN)
                .debounce(3000L)
                .provider("pigpio-digital-input");
        DigitalInput button = pi4j.create(buttonConfig);
        button.addListener(e -> {
            if (e.state() == DigitalState.LOW) {

                switch (led.state()) {
                    case LOW:
                        led.on();
                        System.out.println("开灯");
                        break;
                    case HIGH:
                        led.off();
                        System.out.println("关灯");
                    default:
                        led.off();
                        break;
                }
            }
        });
    }

}
